#include "windows.h"
#include "..\include\CGameClass.h"
#include "..\include\CTimer.h"

#define WNDCLASSNAME "wndclass"
#define WNDTITLE "Init D3D"

#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600

HDC hdc;
HWND hwnd;
CTimer* pTimer = new CTimer();
CGameClass* pGame = CGameClass::GetInstance();

bool quit = false;

LRESULT CALLBACK WinProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam);


// WINMAIN
int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpcmdline, int nshowcmd)
{
	MSG msg;
	WNDCLASSEX ex;

	ex.cbSize = sizeof(WNDCLASSEX);
	ex.style = CS_HREDRAW|CS_VREDRAW|CS_OWNDC;
	ex.lpfnWndProc = WinProc;
	ex.cbClsExtra = 0;
	ex.cbWndExtra = 0;
	ex.hInstance = hinstance;
	ex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	ex.hCursor = LoadCursor(NULL, IDC_ARROW);
	ex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	ex.lpszMenuName = NULL;
	ex.lpszClassName = WNDCLASSNAME;
	ex.hIconSm = NULL;

	RegisterClassEx(&ex);

	// Create the window
	hwnd = CreateWindowEx(NULL,
 			      WNDCLASSNAME,
			      WNDTITLE,
			      WS_OVERLAPPEDWINDOW,
			      0, 0,
			      SCREEN_WIDTH, SCREEN_HEIGHT,
			      NULL,
			      NULL,
			      hinstance,
			      NULL);
pTimer->StartTimer();
	
	ShowWindow(hwnd, SW_SHOW);
	UpdateWindow(hwnd);

	pGame->Initialize(SCREEN_WIDTH, SCREEN_HEIGHT, hwnd);

	

	// The message loop
	while(!quit)
	{
	  if(PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE))
	  {
	    if(msg.message == WM_QUIT)
	      quit = true;
	  
            TranslateMessage(&msg);
			DispatchMessage(&msg);
	  }
	  else
	  {
			if(pTimer)
				pTimer->UpdateTimer();

			char buffer[16] = {0};
			sprintf_s(buffer, sizeof(buffer), "FPS - %.2f", pTimer->GetFPS());
			SetWindowText(hwnd, buffer);

			pGame->Update(pTimer->GetElapsedTime());
			pGame->Draw(pTimer->GetElapsedTime());
	  }
	}

	delete pTimer;
	pGame->CleanUp();

	return msg.lParam;
}

// THE WINDOW EVENT HANDLER
LRESULT CALLBACK WinProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
	switch(msg)
	{
	case WM_CLOSE:
		PostQuitMessage(0);
		break;

	case WM_KEYDOWN:
		switch(wparam)
		{
		case VK_ESCAPE:
			PostQuitMessage(0);
			break;
		}
		break;

	case WM_RBUTTONDOWN:
		pGame->OnRightMouseClick(LOWORD(lparam), HIWORD(lparam));
		break;

	case WM_MOUSEMOVE:
		switch(wparam)
		{
		case MK_RBUTTON:
			pGame->OnMouseMove(LOWORD(lparam), HIWORD(lparam));
			break;
		}
		break;


	default:
		break;
	}






  return DefWindowProc(hwnd, msg, wparam, lparam);
}